<template>
  <div class="resource-page">
    <!-- 调试信息区域 -->
    <div v-if="false" class="debug-info" style="background: #f0f0f0; padding: 10px; margin-bottom: 20px; border-radius: 4px;">
      <h4>调试信息：</h4>
      <p>是否登录: {{ isLoggedIn }}</p>
      <p>Token: {{ token ? '存在' : '不存在' }}</p>
      <p>用户信息: {{ userInfo ? JSON.stringify(userInfo) : '无' }}</p>
    </div>
    
    <div class="resource-container">
      <!-- 游客模式提示 -->
      <el-alert
        v-if="!isLoggedIn"
        title="当前为游客模式"
        type="info"
        description="您可以浏览资源列表，但下载、上传、预订等功能需要登录后使用"
        show-icon
        :closable="false"
        style="margin-bottom: 20px;"
      />
      
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>资源共享</h2>
        <p>教学课件、科研资料、图书文献、共享设备等资源的统一管理平台</p>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-row :gutter="20" align="middle">
        <el-col :span="3">
          <el-select v-model="filterCategory" placeholder="选择分类" style="width: 100%" @change="handleSearch">
            <el-option label="全部分类" value="" />
            <el-option label="教学课件" value="TEACHING" />
            <el-option label="科研资料" value="SCIENTIFIC" />
            <el-option label="图书文献" value="LITERATURE" />
            <el-option label="共享设备" value="EQUIPMENT" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select v-model="filterType" placeholder="选择类型" style="width: 100%" @change="handleSearch">
            <el-option label="全部类型" value="" />
            <el-option label="文档" value="DOCUMENT" />
            <el-option label="设备" value="EQUIPMENT" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索资源标题、描述或标签"
            prefix-icon="Search"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </el-col>
        <el-col :span="10" style="text-align: right;">
        <el-button type="primary" @click="showUploadDialog = true" v-if="canUpload">
          <el-icon><Upload /></el-icon>
          上传资源
        </el-button>
        <el-button type="warning" @click="openMyBookingsDialog" :disabled="!isLoggedIn">
          <el-icon><Calendar /></el-icon>
          我的预约
        </el-button>
        </el-col>
      </el-row>
      
      <!-- 筛选状态提示 -->
      <div class="filter-status" v-if="hasActiveFilters">
        <el-tag type="info" size="small">
          <el-icon><Search /></el-icon>
          当前筛选：
          <span v-if="filterCategory">{{ getCategoryName(filterCategory) }}</span>
          <span v-if="filterType">{{ getTypeName(filterType) }}</span>
          <span v-if="searchKeyword">关键词："{{ searchKeyword }}"</span>
          <el-button 
            type="text" 
            size="small" 
            @click="clearFilters"
            style="margin-left: 8px; color: #409EFF;"
          >
            清除筛选
          </el-button>
        </el-tag>
      </div>
    </div>

    <!-- 资源列表 -->
    <div class="resource-list">
      <el-row :gutter="20">
        <el-col :span="8" v-for="resource in resourceList" :key="resource.id">
          <el-card class="resource-item" shadow="hover">
            <div class="resource-header">
              <div class="resource-title">
                <el-tag :type="getCategoryTagType(resource.category)" size="small">
                  {{ getCategoryName(resource.category) }}
                </el-tag>
                <el-tag :type="getTypeTagType(resource.type)" size="small" style="margin-left: 8px;">
                  {{ getTypeName(resource.type) }}
                </el-tag>
                <span class="title-text">{{ resource.title }}</span>
              </div>
            </div>
            
            <div class="resource-content">
              <p class="description">{{ resource.description }}</p>
              <div class="file-info" v-if="resource.type === 'DOCUMENT'">
                <el-icon><Document /></el-icon>
                <span>{{ resource.fileName }}</span>
                <span class="file-size">({{ formatFileSize(resource.fileSize) }})</span>
              </div>
              <div class="equipment-info" v-if="resource.type === 'EQUIPMENT'">
                <el-icon><Monitor /></el-icon>
                <span>设备信息</span>
              </div>
            </div>
            
            <div class="resource-meta">
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>上传者：{{ resource.uploaderName }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span>上传时间：{{ formatDate(resource.createTime) }}</span>
              </div>
              <div class="meta-item">
                <el-icon><View /></el-icon>
                <span>浏览：{{ resource.viewCount }}</span>
              </div>
              <div class="meta-item" v-if="resource.type === 'DOCUMENT'">
                <el-icon><Download /></el-icon>
                <span>下载：{{ resource.downloadCount }}</span>
              </div>
            </div>
            
            <div class="resource-footer">
              <el-button type="primary" size="small" @click="viewResourceDetail(resource)">
                查看详情
              </el-button>
              <el-button 
                v-if="resource.type === 'DOCUMENT'" 
                type="success" 
                size="small" 
                @click="downloadResource(resource)"
              >
                下载
              </el-button>
              <el-button 
                v-if="resource.type === 'EQUIPMENT'" 
                type="warning" 
                size="small" 
                @click="bookResource(resource)"
              >
                预订
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48, 96]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 上传资源对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传资源"
      width="60%"
      :before-close="handleCloseUpload"
    >
      <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" label-width="100px">
        <el-form-item label="资源标题" prop="title">
          <el-input v-model="uploadForm.title" placeholder="请输入资源标题" />
        </el-form-item>
        
        <el-form-item label="资源分类" prop="category">
          <el-select v-model="uploadForm.category" placeholder="请选择资源分类" style="width: 100%">
            <el-option label="教学课件" value="TEACHING" />
            <el-option label="科研资料" value="SCIENTIFIC" />
            <el-option label="图书文献" value="LITERATURE" />
            <el-option label="共享设备" value="EQUIPMENT" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="资源类型" prop="type">
          <el-input v-model="uploadForm.type" :readonly="true" style="width: 100%" disabled />
        </el-form-item>
        
        <el-form-item label="资源描述" prop="description">
          <el-input 
            v-model="uploadForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入资源描述"
          />
        </el-form-item>
        
        <el-form-item label="标签" prop="tags">
          <el-input v-model="uploadForm.tags" placeholder="请输入标签，多个标签用逗号分隔" />
        </el-form-item>
        
        <el-form-item label="上传文件" prop="file" v-if="uploadForm.type === 'DOCUMENT'">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.zip,.rar"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持PDF、Word、PPT、Excel、TXT、ZIP、RAR格式，文件大小不超过50MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="设备信息" prop="equipmentInfo" v-if="uploadForm.type === 'EQUIPMENT'">
          <el-input 
            v-model="uploadForm.equipmentInfo" 
            type="textarea" 
            :rows="3"
            placeholder="请输入设备详细信息（JSON格式）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUploadDialog = false">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploading">
            上传
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 资源详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="资源详情"
      width="70%"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentResource" class="resource-detail">
        <div class="detail-header">
          <h3>{{ currentResource.title }}</h3>
          <div class="detail-meta">
            <el-tag type="info" size="small">编号：{{ currentResource.resourceId }}</el-tag>
            <el-tag :type="getCategoryTagType(currentResource.category)">
              {{ getCategoryName(currentResource.category) }}
            </el-tag>
            <el-tag :type="getTypeTagType(currentResource.type)" style="margin-left: 8px;">
              {{ getTypeName(currentResource.type) }}
            </el-tag>
            <el-tag :type="getStatusTagType(currentResource.status)" style="margin-left: 8px;">
              {{ getStatusName(currentResource.status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-content">
          <p><strong>描述：</strong>{{ currentResource.description }}</p>
          
          <div v-if="currentResource.type === 'DOCUMENT'" class="file-detail">
            <p><strong>文件名：</strong>{{ currentResource.fileName }}</p>
            <p><strong>文件大小：</strong>{{ formatFileSize(currentResource.fileSize) }}</p>
            <p><strong>文件类型：</strong>{{ currentResource.fileExtension?.toUpperCase() }}</p>
          </div>
          
          <div v-if="currentResource.type === 'EQUIPMENT'" class="equipment-detail">
            <p><strong>设备信息：</strong></p>
            <pre>{{ currentResource.equipmentInfo }}</pre>
          </div>
          
          <div class="detail-info">
            <p><strong>上传者：</strong>{{ currentResource.uploaderName }}</p>
            <p><strong>上传时间：</strong>{{ formatDate(currentResource.createTime) }}</p>
            <p><strong>浏览次数：</strong>{{ currentResource.viewCount }}</p>
            <p v-if="currentResource.type === 'DOCUMENT'"><strong>下载次数：</strong>{{ currentResource.downloadCount }}</p>
            <p v-if="currentResource.tags"><strong>标签：</strong>{{ currentResource.tags }}</p>
          </div>
        </div>
        
        <div class="detail-actions">
          <el-button 
            v-if="currentResource.type === 'DOCUMENT'" 
            type="primary" 
            @click="downloadResource(currentResource)"
          >
            <el-icon><Download /></el-icon>
            下载资源
          </el-button>
          <el-button 
            v-if="currentResource.type === 'EQUIPMENT'" 
            type="warning" 
            @click="bookResource(currentResource)"
          >
            <el-icon><Calendar /></el-icon>
            预订设备
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 预订设备对话框 -->
    <el-dialog
      v-model="showBookingDialog"
      title="预订设备"
      width="50%"
      :before-close="handleCloseBooking"
    >
      <el-form :model="bookingForm" :rules="bookingRules" ref="bookingFormRef" label-width="100px">
        <el-form-item label="预订日期" prop="bookingDate">
          <el-date-picker
            v-model="bookingForm.bookingDate"
            type="date"
            placeholder="选择预订日期"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            v-model="bookingForm.startTime"
            placeholder="选择开始时间"
            style="width: 100%"
            format="HH:mm"
            value-format="HH:mm"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker
            v-model="bookingForm.endTime"
            placeholder="选择结束时间"
            style="width: 100%"
            format="HH:mm"
            value-format="HH:mm"
          />
        </el-form-item>
        
        <el-form-item label="使用目的" prop="purpose">
          <el-input 
            v-model="bookingForm.purpose" 
            type="textarea" 
            :rows="3"
            placeholder="请描述使用目的"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showBookingDialog = false">取消</el-button>
          <el-button type="primary" @click="submitBooking" :loading="booking">
            提交预订
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 我的预约对话框 -->
    <el-dialog
      v-model="showMyBookingsDialog"
      title="我的预约"
      width="80%"
      :before-close="handleCloseMyBookings"
    >
      <div class="my-bookings-content">
        <el-table :data="myBookingsList" v-loading="myBookingsLoading" style="width: 100%">
          <el-table-column prop="resourceTitle" label="设备名称" min-width="150" />
          <el-table-column prop="bookingDate" label="预约日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.bookingDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="100" />
          <el-table-column prop="endTime" label="结束时间" width="100" />
          <el-table-column prop="purpose" label="使用目的" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getBookingStatusTagType(scope.row.status)">
                {{ getBookingStatusName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="预约时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button 
                v-if="scope.row.status === 'PENDING'" 
                type="danger" 
                size="small" 
                @click="cancelBooking(scope.row.id)"
              >
                取消预约
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section" style="margin-top: 20px;">
          <el-pagination
            v-model:current-page="myBookingsCurrentPage"
            v-model:page-size="myBookingsPageSize"
            :page-sizes="[10, 20, 50]"
            :total="myBookingsTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleMyBookingsSizeChange"
            @current-change="handleMyBookingsCurrentChange"
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMyBookingsDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Upload, 
  Document, 
  Monitor, 
  User, 
  Clock, 
  View, 
  Download, 
  Calendar 
} from '@element-plus/icons-vue'
import { getResourceList, uploadResource, createBooking, getResourceListPublic, getMyBookings, cancelBooking as cancelBookingApi, checkBookingConflict } from '@/api/resource'

export default {
  name: 'ResourcePage',
  components: {
    Search,
    Upload,
    Document,
    Monitor,
    User,
    Clock,
    View,
    Download,
    Calendar
  },
  setup() {
    const store = useStore()
    
    // 用户信息 - 修复：使用store的getters获取用户信息
    const userInfo = computed(() => store.getters['user/userInfo'])
    const isLoggedIn = computed(() => store.getters['user/isLoggedIn'])
    const token = computed(() => store.getters['user/token'])
    
    // 计算用户是否有上传权限（教师或管理员）
    const canUpload = computed(() => {
      if (!isLoggedIn.value || !userInfo.value) return false
      const role = userInfo.value.role
      return role === 'TEACHER' || role === 'ADMIN'
    })
    
    // 筛选和搜索
    const filterCategory = ref('')
    const filterType = ref('')
    const searchKeyword = ref('')
    
    // 计算是否有活跃的筛选条件
    const hasActiveFilters = computed(() => {
      return (filterCategory.value && filterCategory.value.trim()) ||
             (filterType.value && filterType.value.trim()) ||
             (searchKeyword.value && searchKeyword.value.trim())
    })
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(12)
    const total = ref(0)
    
    // 数据
    const resourceList = ref([])
    const loading = ref(false)
    
    // 我的预约数据
    const myBookingsList = ref([])
    const myBookingsLoading = ref(false)
    const myBookingsCurrentPage = ref(1)
    const myBookingsPageSize = ref(10)
    const myBookingsTotal = ref(0)
    
    // 对话框控制
    const showUploadDialog = ref(false)
    const detailVisible = ref(false)
    const showBookingDialog = ref(false)
    const showMyBookingsDialog = ref(false)
    const currentResource = ref(null)
    
    // 上传表单
    const uploadFormRef = ref()
    const uploadRef = ref()
    const uploading = ref(false)
    const uploadForm = reactive({
      title: '',
      category: '',
      type: '',
      description: '',
      tags: '',
      equipmentInfo: '',
      file: null
    })
    
    const uploadRules = {
      title: [{ required: true, message: '请输入资源标题', trigger: 'blur' }],
      category: [{ required: true, message: '请选择资源分类', trigger: 'change' }],
      type: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
      description: [{ required: true, message: '请输入资源描述', trigger: 'blur' }]
    }
    
    // 分类变更时自动设置类型
    watch(() => uploadForm.category, (val) => {
      if (val === 'EQUIPMENT') {
        uploadForm.type = 'EQUIPMENT'
      } else {
        uploadForm.type = 'DOCUMENT'
      }
    }, { immediate: true })
    
    // 预订表单
    const bookingFormRef = ref()
    const booking = ref(false)
    const bookingForm = reactive({
      resourceId: null,
      bookingDate: '',
      startTime: '',
      endTime: '',
      purpose: ''
    })
    
    const bookingRules = {
      bookingDate: [{ required: true, message: '请选择预订日期', trigger: 'change' }],
      startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
      endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' },
        { 
          validator: (rule, value, callback) => {
            if (value && bookingForm.startTime) {
              const startMinutes = timeToMinutes(bookingForm.startTime)
              const endMinutes = timeToMinutes(value)
              if (endMinutes <= startMinutes) {
                callback(new Error('结束时间必须大于开始时间'))
              } else {
                callback()
              }
            } else {
              callback()
            }
          }, 
          trigger: 'change' 
        }
      ],
      purpose: [{ required: true, message: '请输入使用目的', trigger: 'blur' }]
    }
    
    // 辅助方法：将时间字符串转换为分钟数
    const timeToMinutes = (time) => {
      if (!time) return 0
      const parts = time.split(':')
      if (parts.length === 2) {
        const hours = parseInt(parts[0])
        const minutes = parseInt(parts[1])
        return hours * 60 + minutes
      }
      return 0
    }
    
    // 获取资源列表
    const fetchResourceList = async () => {
      loading.value = true
      try {
        const params = {
          current: currentPage.value,
          size: pageSize.value
        }
        
        // 只有当筛选条件不为空时才添加到参数中
        if (filterCategory.value && filterCategory.value.trim()) {
          params.category = filterCategory.value
        }
        
        if (filterType.value && filterType.value.trim()) {
          params.type = filterType.value
        }
        
        if (searchKeyword.value && searchKeyword.value.trim()) {
          params.keyword = searchKeyword.value
        }
        
        console.log('请求参数:', params)
        console.log('用户信息:', userInfo.value)
        console.log('是否登录:', isLoggedIn.value)
        console.log('Token:', token.value)
        
        const response = await getResourceList(params)
        console.log('API响应:', response)
        
        if (response.code === 200) {
          resourceList.value = response.data.records || []
          total.value = response.data.total || 0
          console.log('资源列表:', resourceList.value)
        } else {
          ElMessage.error(response.message || '获取资源列表失败')
        }
      } catch (error) {
        console.error('获取资源列表失败:', error)
        console.error('错误详情:', error.response?.data)
        
        // 如果是401或403错误，尝试不带token重新请求
        if (error.response?.status === 401 || error.response?.status === 403) {
          console.log('Token验证失败或无权限，尝试不带token请求...')
          try {
            const params = {
              current: currentPage.value,
              size: pageSize.value
            }
            
            // 只有当筛选条件不为空时才添加到参数中
            if (filterCategory.value && filterCategory.value.trim()) {
              params.category = filterCategory.value
            }
            
            if (filterType.value && filterType.value.trim()) {
              params.type = filterType.value
            }
            
            if (searchKeyword.value && searchKeyword.value.trim()) {
              params.keyword = searchKeyword.value
            }
            
            const response = await getResourceListPublic(params)
            
            if (response.code === 200) {
              resourceList.value = response.data.records || []
              total.value = response.data.total || 0
              console.log('不带token请求成功，资源列表:', resourceList.value)
              ElMessage.warning('当前为游客模式，部分功能受限')
            } else {
              ElMessage.error(response.message || '获取资源列表失败')
            }
          } catch (retryError) {
            console.error('不带token请求也失败:', retryError)
            ElMessage.error('获取资源列表失败，请检查网络连接')
          }
        } else {
          ElMessage.error(`获取资源列表失败: ${error.message}`)
        }
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchResourceList()
    }
    
    // 清除所有筛选条件
    const clearFilters = () => {
      filterCategory.value = ''
      filterType.value = ''
      searchKeyword.value = ''
      currentPage.value = 1
      fetchResourceList()
    }
    
    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchResourceList()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchResourceList()
    }
    
    // 文件处理
    const handleFileChange = (file) => {
      uploadForm.file = file.raw
    }
    
    const handleFileRemove = () => {
      uploadForm.file = null
    }
    
    // 上传资源
    const submitUpload = async () => {
      // 检查用户是否登录
      if (!isLoggedIn.value || !token.value) {
        ElMessage.warning('请先登录后再上传资源')
        return
      }
      
      // 检查用户是否有上传权限（教师或管理员）
      if (!canUpload.value) {
        ElMessage.error('您没有上传资源的权限，只有教师和管理员可以上传资源')
        return
      }
      
      if (!uploadFormRef.value) return
      
      const valid = await uploadFormRef.value.validate()
      if (!valid) return
      
      if (uploadForm.type === 'DOCUMENT' && !uploadForm.file) {
        ElMessage.error('请选择要上传的文件')
        return
      }
      
      uploading.value = true
      try {
        const formData = new FormData()
        formData.append('title', uploadForm.title)
        formData.append('description', uploadForm.description)
        formData.append('category', uploadForm.category)
        formData.append('type', uploadForm.type)
        formData.append('tags', uploadForm.tags)
        
        if (uploadForm.type === 'DOCUMENT' && uploadForm.file) {
          formData.append('file', uploadForm.file)
        }
        
        if (uploadForm.type === 'EQUIPMENT') {
          formData.append('equipmentInfo', uploadForm.equipmentInfo)
        }
        
        const response = await uploadResource(formData)
        if (response.code === 200) {
          ElMessage.success('资源上传成功，等待管理员审核')
          showUploadDialog.value = false
          resetUploadForm()
          fetchResourceList()
        } else {
          ElMessage.error(response.message || '上传失败')
        }
      } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('上传失败')
      } finally {
        uploading.value = false
      }
    }
    
    // 重置上传表单
    const resetUploadForm = () => {
      uploadForm.title = ''
      uploadForm.category = ''
      uploadForm.type = ''
      uploadForm.description = ''
      uploadForm.tags = ''
      uploadForm.equipmentInfo = ''
      uploadForm.file = null
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
    }
    
    // 查看资源详情
    const viewResourceDetail = (resource) => {
      currentResource.value = resource
      detailVisible.value = true
    }
    
    // 下载资源
    const downloadResource = async (resource) => {
      if (!isLoggedIn.value || !token.value) {
        ElMessage.warning('请先登录后再下载资源')
        return
      }
      try {
        // 从fileUrl中提取文件名
        let fileName = resource.fileUrl
        if (fileName && fileName.startsWith('/uploads/')) {
          fileName = fileName.substring(9) // 去掉'/uploads/'前缀
        }
        // 直接跳转到下载接口
        window.open(`/api/download/${fileName}`, '_blank')
        ElMessage.success('开始下载')
      } catch (error) {
        console.error('下载失败:', error)
        ElMessage.error('下载失败')
      }
    }
    
    // 预订设备
    const bookResource = (resource) => {
      // 检查用户是否登录
      if (!isLoggedIn.value || !token.value) {
        ElMessage.warning('请先登录后再预订资源')
        return
      }
      
      bookingForm.resourceId = resource.id
      showBookingDialog.value = true
    }
    
    // 提交预订
    const submitBooking = async () => {
      if (!bookingFormRef.value) return
      
      const valid = await bookingFormRef.value.validate()
      if (!valid) return
      
      booking.value = true
      try {
        // 先检查时间冲突
        const conflictCheck = await checkBookingConflict({
          resourceId: bookingForm.resourceId,
          bookingDate: bookingForm.bookingDate,
          startTime: bookingForm.startTime,
          endTime: bookingForm.endTime
        })
        
        if (conflictCheck.code !== 200) {
          ElMessage.error(conflictCheck.message || '时间冲突检查失败')
          return
        }
        
        // 检查是否有冲突
        if (conflictCheck.conflict) {
          ElMessage.error(conflictCheck.message || '该时间段已被预约，请选择其他时间')
          return
        }
        
        const response = await createBooking({
          resourceId: bookingForm.resourceId,
          bookingDate: bookingForm.bookingDate,
          startTime: bookingForm.startTime,
          endTime: bookingForm.endTime,
          purpose: bookingForm.purpose
        })
        
        if (response.code === 200) {
          ElMessage.success('预订申请提交成功，等待审批')
          showBookingDialog.value = false
          resetBookingForm()
          fetchMyBookings()
        } else {
          ElMessage.error(response.message || '预订失败')
        }
      } catch (error) {
        console.error('预订失败:', error)
        ElMessage.error('预订失败')
      } finally {
        booking.value = false
      }
    }
    
    // 重置预订表单
    const resetBookingForm = () => {
      bookingForm.resourceId = null
      bookingForm.bookingDate = ''
      bookingForm.startTime = ''
      bookingForm.endTime = ''
      bookingForm.purpose = ''
    }
    
    // 关闭对话框
    const handleCloseUpload = () => {
      showUploadDialog.value = false
      resetUploadForm()
    }
    
    const handleCloseDetail = () => {
      detailVisible.value = false
      currentResource.value = null
    }
    
    const handleCloseBooking = () => {
      showBookingDialog.value = false
      resetBookingForm()
    }
    
    // 禁用过去的日期
    const disabledDate = (time) => {
      return time.getTime() < Date.now() - 8.64e7
    }
    
    // 工具函数
    const getCategoryName = (category) => {
      const categoryMap = {
        'TEACHING': '教学课件',
        'SCIENTIFIC': '科研资料',
        'LITERATURE': '图书文献',
        'EQUIPMENT': '共享设备'
      }
      return categoryMap[category] || category
    }
    
    const getTypeName = (type) => {
      const typeMap = {
        'DOCUMENT': '文档',
        'EQUIPMENT': '设备'
      }
      return typeMap[type] || type
    }
    
    const getCategoryTagType = (category) => {
      const typeMap = {
        'TEACHING': 'primary',
        'SCIENTIFIC': 'success',
        'LITERATURE': 'warning',
        'EQUIPMENT': 'info'
      }
      return typeMap[category] || ''
    }
    
    const getTypeTagType = (type) => {
      return type === 'DOCUMENT' ? 'danger' : 'warning'
    }
    
    const getStatusTagType = (status) => {
      const typeMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger'
      }
      return typeMap[status] || ''
    }
    
    const getStatusName = (status) => {
      const statusMap = {
        'PENDING': '待审核',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝'
      }
      return statusMap[status] || status
    }
    
    const getBookingStatusTagType = (status) => {
      const typeMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return typeMap[status] || ''
    }
    
    const getBookingStatusName = (status) => {
      const statusMap = {
        'PENDING': '待审批',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    const formatFileSize = (bytes) => {
      if (!bytes) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN')
    }
    
    // 获取我的预约列表
    const fetchMyBookings = async () => {
      myBookingsLoading.value = true
      try {
        const params = {
          current: myBookingsCurrentPage.value,
          size: myBookingsPageSize.value
        }
        const response = await getMyBookings(params)
        if (response.code === 200) {
          myBookingsList.value = response.data || []
          myBookingsTotal.value = (response.data && response.data.length) || 0
        } else {
          ElMessage.error(response.message || '获取预约列表失败')
        }
      } catch (error) {
        console.error('获取预约列表失败:', error)
        ElMessage.error('获取预约列表失败')
      } finally {
        myBookingsLoading.value = false
      }
    }
    
    // 取消预约
    const cancelBooking = async (bookingId) => {
      try {
        await ElMessageBox.confirm('确定要取消这个预约吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await cancelBookingApi(bookingId)
        if (response.code === 200) {
          ElMessage.success('预约已取消')
          fetchMyBookings()
        } else {
          ElMessage.error(response.message || '取消预约失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消预约失败:', error)
          ElMessage.error('取消预约失败')
        }
      }
    }
    
    // 我的预约分页处理
    const handleMyBookingsSizeChange = (val) => {
      myBookingsPageSize.value = val
      myBookingsCurrentPage.value = 1
      fetchMyBookings()
    }
    
    const handleMyBookingsCurrentChange = (val) => {
      myBookingsCurrentPage.value = val
      fetchMyBookings()
    }
    
    // 关闭我的预约对话框
    const handleCloseMyBookings = () => {
      showMyBookingsDialog.value = false
    }
    
    // 打开我的预约对话框时获取数据
    const openMyBookingsDialog = () => {
      showMyBookingsDialog.value = true
      myBookingsCurrentPage.value = 1
      fetchMyBookings()
    }
    
    // 初始化
    onMounted(() => {
      // 确保用户信息是最新的
      if (isLoggedIn.value && (!userInfo.value || !userInfo.value.id)) {
        console.log('用户已登录但信息不完整，尝试刷新用户信息')
        store.dispatch('user/refreshUserInfo')
      }
      fetchResourceList()
    })
    
    return {
      userInfo,
      isLoggedIn,
      token,
      filterCategory,
      filterType,
      searchKeyword,
      hasActiveFilters,
      currentPage,
      pageSize,
      total,
      resourceList,
      loading,
      showUploadDialog,
      detailVisible,
      showBookingDialog,
      showMyBookingsDialog,
      currentResource,
      uploadFormRef,
      uploadRef,
      uploading,
      uploadForm,
      uploadRules,
      bookingFormRef,
      booking,
      bookingForm,
      bookingRules,
      myBookingsList,
      myBookingsLoading,
      myBookingsTotal,
      myBookingsCurrentPage,
      myBookingsPageSize,
      handleSearch,
      clearFilters,
      handleSizeChange,
      handleCurrentChange,
      handleFileChange,
      handleFileRemove,
      submitUpload,
      viewResourceDetail,
      downloadResource,
      bookResource,
      submitBooking,
      handleCloseUpload,
      handleCloseDetail,
      handleCloseBooking,
      disabledDate,
      getCategoryName,
      getTypeName,
      getCategoryTagType,
      getTypeTagType,
      getStatusTagType,
      getStatusName,
      formatFileSize,
      formatDate,
      getBookingStatusTagType,
      getBookingStatusName,
      fetchMyBookings,
      cancelBooking,
      handleMyBookingsSizeChange,
      handleMyBookingsCurrentChange,
      handleCloseMyBookings,
      openMyBookingsDialog,
      canUpload
    }
  }
}
</script>

<style scoped>
.resource-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.filter-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.filter-status {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.resource-list {
  margin-bottom: 30px;
}

.resource-item {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.resource-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.resource-header {
  margin-bottom: 15px;
}

.resource-title {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.title-text {
  font-weight: bold;
  color: #303133;
  margin-left: 8px;
}

.resource-content {
  margin-bottom: 15px;
}

.description {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.file-info,
.equipment-info {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  font-size: 12px;
}

.file-size {
  color: #c0c4cc;
}

.resource-meta {
  margin-bottom: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  font-size: 12px;
  margin-bottom: 5px;
}

.resource-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.resource-detail {
  padding: 20px 0;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.detail-header h3 {
  color: #303133;
  margin-bottom: 10px;
}

.detail-meta {
  display: flex;
  gap: 8px;
}

.detail-content {
  margin-bottom: 20px;
}

.detail-content p {
  margin-bottom: 10px;
  line-height: 1.6;
}

.file-detail,
.equipment-detail {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin: 15px 0;
}

.equipment-detail pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.detail-info {
  background: #fafafa;
  padding: 15px;
  border-radius: 4px;
  margin: 15px 0;
}

.detail-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 